const express = require('express');
const cors = require('cors');
const { Todo } = require('./database');

const app = express();
const PORT = process.env.PORT || 3000;

app.use(cors());
app.use(express.json());
app.use(express.static('public'));

// 获取所有待办事项
app.get('/api/todos', (req, res) => {
  Todo.getAll((err, todos) => {
    if (err) {
      res.status(500).json({ error: err.message });
    } else {
      res.json(todos);
    }
  });
});

// 创建新的待办事项
app.post('/api/todos', (req, res) => {
  const { title } = req.body;
  if (!title || title.trim() === '') {
    return res.status(400).json({ error: 'Title is required' });
  }

  Todo.create(title.trim(), (err, todo) => {
    if (err) {
      res.status(500).json({ error: err.message });
    } else {
      res.status(201).json(todo);
    }
  });
});

// 更新待办事项
app.put('/api/todos/:id', (req, res) => {
  const id = parseInt(req.params.id);
  const { title, completed } = req.body;

  Todo.update(id, { title, completed }, (err) => {
    if (err) {
      res.status(500).json({ error: err.message });
    } else {
      res.json({ message: 'Todo updated successfully' });
    }
  });
});

// 删除待办事项
app.delete('/api/todos/:id', (req, res) => {
  const id = parseInt(req.params.id);

  Todo.delete(id, (err) => {
    if (err) {
      res.status(500).json({ error: err.message });
    } else {
      res.json({ message: 'Todo deleted successfully' });
    }
  });
});

app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});
